<template>
    <div>
      <!-- 使用 v-model 指令实现双向数据绑定 -->
      <p>Ask a yes/no question: <input v-model="question"></p>
      <p>{{ answer }}</p>
    </div>
  </template>
  
  <script setup>
  import { ref, watchEffect } from 'vue'
  import axios from 'axios'
  
  // 定义响应式数据
  const question = ref('')
  const answer = ref('I cannot give you an answer until you ask a question!')
  
  // 定义响应式监听，用来监听 question 的变化
  watchEffect(() => {
    // 如果 question 为空，就重置 answer
    if (question.value === '') {
      answer.value = 'I cannot give you an answer until you ask a question!'
    // 如果 question 以 ? 结尾，就调用一个异步的 API 来获取 answer
    } else if (question.value.endsWith('?')) {
      answer.value = 'Waiting for you to stop typing...'
      getAnswer()
    // 否则，就提示 question 必须是一个问题
    } else {
      answer.value = 'Questions usually contain a question mark. ;-)'
    }
  })
  
  // 定义一个方法，用来调用一个异步的 API
  const getAnswer = async () => {
    // 使用 axios 发送一个 GET 请求
    try {
      const response = await axios.get('https://yesno.wtf/api')
      // 如果请求成功，就将 answer 设置为 API 返回的结果
      answer.value = response.data.answer
    } catch (error) {
      // 如果请求失败，就将 answer 设置为错误信息
      answer.value = 'Error! Could not reach the API. ' + error
    }
  }
  </script>